// Example express application adding the parse-server module to expose Parse
// compatible API routes.

var express = require('express');
var ParseServer = require('jst-server').ParseServer;
var path = require('path');
var request = require('request');

var app = express();

// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
var mountPath = process.env.PARSE_MOUNT || '/v1';

function invalidRequest(req, res) {
    res.status(403);
    //res.end('{"error":"unauthorized"}');
    res.end('{"error":"认证失败"}');
}

app.use(mountPath, function(req, res, next) {
    var appId = req.get('X-JST-Application-Id');
    if (!appId || typeof(appId) !== "string") {
        return invalidRequest(req, res);
    }
    var options = {
        url: 'http://apibase.jishutuan.com/v1/classes/apps/' + appId,
        headers: {
            'X-Parse-Application-Id': 'apiBaseAppId',
            'Content-Type': 'application/json'
        }
    };

    request(options, function(error, response, body) {
        if (error) {
            console.log('error', error);
            return;
        }
        var info = JSON.parse(body);
        if (info.code === 101) {
            return invalidRequest(req, res);
        }
        var api = new ParseServer({
            databaseURI: 'mongodb://superuser:pwd@mongodb.jishutuan.com/' + info.objectId + '?authSource=admin',
            cloud: __dirname + '/cloud/main.js',
            appId: info.objectId,
            masterKey: info.masterKey,
            restAPIKey: info.restAPIKey,
            serverURL: 'https://api.jishutuan.com/' // Don't forget to change to https if needed
        });
        api(req, res, next);

    });
});

// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
    res.status(200).send('欢迎使用微信小程序数据接口，本接口由技术团提供，基于Parse,Mongo创建，使用Docker部署。');
});

// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
    res.sendFile(path.join(__dirname, '/public/test.html'));
});

var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server running on port ' + port + '.');
});

// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
